package bio.socket;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * Instruction：
 * Author：@author MaLi
 */
public class FileTransferClient {
    public void startClient() {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress("localhost", 8888));
            //接收控制台输入
            String fileName = getFileName();
            //发送文件名给服务端
            sendFileName(socket, fileName);
            //接收服务端的文件传输
            receiveAndSave(socket, fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String getFileName() {
        //接收控制台输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要获取的文件名: ");
        String fileName = scanner.nextLine().trim();
        return fileName;
    }

    private void sendFileName(Socket socket, String fileName) throws IOException {
        //发送请求的文件名
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write(fileName);
        writer.newLine();
        writer.flush();
    }

    private void receiveAndSave(Socket socket, String fileName) throws IOException {
        //接收文件传输
        try (BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());
             BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(fileName + "_client"))) {
            int length;
            byte[] buffer = new byte[8192];
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.flush();
        }
    }

    public static void main(String[] args) {
        new FileTransferClient().startClient();
    }
}
